extends Weapon

const PROJECTILE_BULLET = preload("res://scenes/weapons/projectile_bullet.tscn")
const CASING_762X_39 = preload("res://scenes/weapons/ammo/762x39/casing_762x39.tscn")

@onready var bullet_spawn: Node3D = $folder/bullet_spawn
@onready var animation_player: AnimationPlayer = $folder/AnimationPlayer
@onready var flash: GPUParticles3D = $folder/flash

const MAX_AMMO = 10

var ammo = 10
var damage = 1
var velocity = 500
var interrupt_reload = false

func _ready() -> void:
	animation_player.animation_finished.connect(_on_animation_ended)
	pass

func fire() -> void:
	if !interrupt_reload && !can_fire && ammo > 0:
		print('Interrupting reload')
		interrupt_reload = true
	if animation_player.is_playing() || ammo < 1 || !can_fire:
		return
	flash.emitting = true
	var bullet = PROJECTILE_BULLET.instantiate()
	add_child(bullet)
	bullet.top_level = true
	bullet.global_position = bullet_spawn.global_position
	bullet.linear_velocity = -bullet.basis.z * velocity
	if ammo == 1:
		animation_player.play("bolt_hold")
	else:
		animation_player.play("bolt_cycle")
	ammo -= 1
	recoil()
	var case = CASING_762X_39.instantiate()
	add_child(case)
	case.top_level = true
	var impulse_vector = case.transform.basis.x + case.transform.basis.y
	impulse_vector.x += randf_range(0.2, 0.5)
	impulse_vector.y += randf_range(0.2, 0.5)
	var player = find_parent('Player')
	if player:
		case.linear_velocity = player.velocity
	case.apply_impulse(
		impulse_vector, 
		Vector3(0,0,randf_range(0.1, 0.2))
		)

func reload() -> void:
	if ammo == MAX_AMMO || animation_player.is_playing():
		return
	can_fire = false
	
	if ammo > 0 && ammo < MAX_AMMO:
		animation_player.play("manual_open_bolt")
	else:
		animation_player.play("turn_to_reload")

func _on_animation_ended(anim_name: String) -> void:
	if anim_name == "manual_open_bolt":
		animation_player.play("load_bullet")
	if anim_name == "turn_to_reload":
		animation_player.play("load_clip")
	if anim_name == "load_clip":
		ammo = MAX_AMMO
		animation_player.play("return_straight")
		interrupt_reload = false
	if anim_name == "load_bullet":
		ammo += 1
		if ammo == MAX_AMMO || interrupt_reload:
			animation_player.play("return_straight")
			interrupt_reload = false
		else:
			animation_player.play("load_bullet")
	if anim_name == "return_straight":
		animation_player.play("bolt_release")
	if anim_name == "bolt_release":
		can_fire = true
